package icu.bughub.app.app.ui.screens

import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.LeadingIconTab
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.TabRowDefaults
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.google.accompanist.placeholder.placeholder
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.SwipeRefreshIndicator
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import icu.bughub.app.app.extension.OnBottomBeached
import icu.bughub.app.app.ui.components.ArticleItem
import icu.bughub.app.app.ui.components.NotificationContent
import icu.bughub.app.app.ui.components.SwiperContent
import icu.bughub.app.app.ui.components.TopAppBar
import icu.bughub.app.app.ui.components.VideoItem
import icu.bughub.app.app.viewmodel.ArticleViewModel
import icu.bughub.app.app.viewmodel.MainViewModel
import icu.bughub.app.app.viewmodel.VideoModel
import kotlinx.coroutines.launch

@Composable
fun StudyScreen(
    viewModel: MainViewModel = viewModel(),
    articleViewModel: ArticleViewModel = viewModel(),
    videoViewModel: VideoModel = viewModel(),
    onNavigateToArticleDetail: () -> Unit = {},
    onNavigateToVideoDetail: () -> Unit = {},
    onNavigateToStudyHistory: () -> Unit = {}
) {

    val coroutineScope = androidx.compose.runtime.rememberCoroutineScope()

    val lazyListState = androidx.compose.foundation.lazy.rememberLazyListState()

    lazyListState.OnBottomBeached(buffer = 3) {
        coroutineScope.launch {
            if (viewModel.showArticleList) {
                articleViewModel.loadMore()
            } else {
                videoViewModel.loadMore()
            }
        }
    }

    LaunchedEffect(Unit) {
        //获取分类数据
        viewModel.getCategoryList()
        //获取文章列表数据
        articleViewModel.fetchArticleList()
        //获取视频列表数据
        videoViewModel.fetchList()
    }

    Column(modifier = Modifier) {
        //标题栏
        TopAppBar(
            modifier = Modifier.padding(horizontal = 10.dp)
        ) {
            //搜索按钮
            Surface(
                modifier = Modifier
                    .clip(shape = RoundedCornerShape(16.dp))
                    .weight(0.8f),
                color = Color(0x33FFFFFF)
            ) {
                Row(
                    modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector = Icons.Default.Search,
                        contentDescription = null,
                        tint = Color.White,
                        modifier = Modifier.size(16.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = "搜索感兴趣的咨询或课程",
                        color = Color.White,
                        fontSize = 12.sp,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }

            Spacer(modifier = Modifier.width(22.dp))
            //学习进度
            Text(
                text = "学习\n进度",
                color = Color.White,
                fontSize = 10.sp,
                maxLines = 2,
                modifier = Modifier
                    .padding(bottom = 4.dp, top = 4.dp)
                    .clickable(enabled = true, onClick = {
                        onNavigateToStudyHistory.invoke()
                    })
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = "26%", color = Color.White, fontSize = 12.sp
            )
            Spacer(modifier = Modifier.width(10.dp))
            Icon(
                imageVector = Icons.Default.Notifications,
                contentDescription = "Notifications",
                tint = Color.White
            )
        }
        //分类标签
        TabRow(
            selectedTabIndex = viewModel.categoryIndex,
            Modifier
                .background(Color(0x22149ee7)),
            contentColor = Color(0x66149ee7),
            divider = {},
            indicator = { tabPositions ->
                TabRowDefaults.PrimaryIndicator(
                    width = 30.dp,
                    height = 2.dp,
                    shape = MaterialTheme.shapes.large,
                    modifier = Modifier
                        .tabIndicatorOffset(tabPositions[viewModel.categoryIndex])
                        .requiredWidth(30.dp)
                        .clip(RoundedCornerShape(18.dp)),
                    color = Color(0x66149ee7)
                )

            }

        ) {
            viewModel.categories.forEachIndexed { index, category ->
                Tab(
                    selected = viewModel.categoryIndex == index,
                    onClick = {
                        viewModel.updateCategoryIndex(index)
                    },
                    selectedContentColor = Color(0x66149ee7),
                    unselectedContentColor = Color(0xFF666666)
                ) {
                    Text(
                        text = category.title,
                        modifier = Modifier
                            .padding(vertical = 8.dp)
                            .placeholder(
                                visible = !viewModel.categoryLoadSuccess,
                                color = Color.LightGray
                            ),
                        fontSize = 14.sp
                    )
                }
            }

        }


        //分类内容
        TabRow(
            selectedTabIndex = viewModel.currentTypeIndex,
            Modifier.background(Color.Transparent),
            contentColor = Color(0x66149ee7),
            divider = {},
            indicator = {}) {
            viewModel.types.forEachIndexed { index, item ->
                //带图标的tab
                LeadingIconTab(
                    selected = viewModel.currentTypeIndex == index,
                    onClick = {
                        viewModel.updateTypeIndex(index)
                    },
                    selectedContentColor = Color(0x66149ee7),
                    unselectedContentColor = Color(0xFF666666),
                    text = {
                        Text(
                            text = item.title,
                            modifier = Modifier.padding(vertical = 8.dp),
                            fontSize = 16.sp
                        )
                    },
                    icon = {
                        Icon(
                            painter = painterResource(item.iconId),
                            contentDescription = item.title,
                            tint = if (index == viewModel.currentTypeIndex) Color(0x66149ee7) else Color(
                                0xFF666666
                            ),
                            modifier = Modifier.size(16.dp)
                        )
                    })
            }
        }

        //banner
        /*
         HorizontalPager(
             state = PagerState {
                 viewModel.swiperData.size
             }, modifier = Modifier
                 .height(180.dp)
                 .padding(horizontal = 8.dp, vertical = 8.dp)

         ) { index ->
             AsyncImage(
                 model = viewModel.swiperData[index].imageUrl,
                 contentDescription = null,
                 modifier = Modifier
                     .fillMaxWidth()
                     .fillMaxHeight()
                     .aspectRatio(7 / 3F)
                     .clip(RoundedCornerShape(8.dp)),
                 contentScale = ContentScale.Crop
             )
         }
 */

        //下拉刷新
        SwipeRefresh(
            state = rememberSwipeRefreshState(if (viewModel.showArticleList) articleViewModel.refresh else videoViewModel.refresh),
            indicator = { state, triggerDistance ->
                SwipeRefreshIndicator(
                    state = state,
                    refreshTriggerDistance = triggerDistance,
                    scale = true,
                    contentColor = Color(0x66149ee7)
                )
            },
            onRefresh = {
                coroutineScope.launch {
                    if (viewModel.showArticleList) {
                        articleViewModel.refresh()
                    } else {
                        videoViewModel.refresh()
                    }
                }
            }) {
            LazyColumn(state = lazyListState) {
                //轮播图
                item {
                    SwiperContent(viewModel = viewModel)
                }
                //通知公告
                item {
                    NotificationContent(viewModel = viewModel)
                }

                if (viewModel.showArticleList) {
                    //新闻列表
                    items(articleViewModel.list.size) { index ->
                        ArticleItem(
                            article = articleViewModel.list[index],
                            articleViewModel.articleLoadSuccess,
                            modifier = Modifier.clickable(enabled = true, onClick = {
                                Log.d("StudyScreen", "onClick")
                                onNavigateToArticleDetail.invoke()
                            })
                        )
                    }
                } else {
                    //视频列表
                    items(videoViewModel.videoList.size) { index ->
                        VideoItem(
                            video = videoViewModel.videoList[index], modifier = Modifier.clickable(
                                enabled = true,
                                onClick = {
                                    onNavigateToVideoDetail()
                                }
                            ), videoViewModel.videoLoadSuccess
                        )
                    }

                }
            }
        }

    }
}

@Preview
@Composable
fun StudyScreenPreview() {
}